//
//  CYLoadingViewController.m
//  cyjf
//
//  Created by tauCross on 2017/6/1.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "CYLoadingViewController.h"

#import <WebKit/WebKit.h>
#import <TCJSONKit.h>
#import <AFNetworking.h>



@interface CYLoadingViewController ()

@property(nonatomic, strong)UIImageView *launchImageView;
@property(nonatomic, strong)WKWebView *webView;

@end


@implementation CYLoadingViewController

- (void)loadUI
{
    NSString *launchImage = nil;
    NSArray *imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
    for(NSDictionary *dict in imagesDict)
    {
        if(CGSizeEqualToSize(CGSizeFromString(dict[@"UILaunchImageSize"]), [[UIScreen mainScreen] bounds].size))
        {
            launchImage = dict[@"UILaunchImageName"];
            break;
        }
    }
    if(launchImage)
    {
        self.launchImageView = [[UIImageView alloc] initWithImage:CYImage(launchImage)];
        [self.contentView addSubview:self.launchImageView];
    }
    else
    {
        self.contentView.backgroundColor = [UIColor whiteColor];
    }
    
    self.webView = [[WKWebView alloc] init];
    self.webView.hidden = YES;
    [self.contentView addSubview:self.webView];
}

- (void)loadData
{
    @weakify(self);
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        @strongify(self);
        if(self)
        {
            if(status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi)
            {
                [[AFNetworkReachabilityManager sharedManager] stopMonitoring];
                [self checkServerAvailable];
            }
        }
    }];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}

- (void)checkServerAvailable
{
    @weakify(self);
    [CYStandardDataAPI user_getSysStatusWithComplete:^(CYResponse *response) {
        @strongify(self);
        if(response.code == 0 && [response.content isKindOfClass:[NSDictionary class]])
        {
            NSString *sysCode = response.content[@"sysCode"];
            if([sysCode isKindOfClass:[NSString class]] && sysCode.integerValue == 1)
            {
                NSString *sysUrl = response.content[@"sysUrl"];
                if([sysUrl isKindOfClass:[NSString class]] && sysUrl.tc_url)
                {
                    [self.webView loadRequest:[NSURLRequest requestWithURL:sysUrl.tc_url]];
                    self.webView.hidden = NO;
                    return;
                }
            }
        }
        if(self.complete)
        {
            self.complete();
        }
    }];
}

- (void)layoutUI
{
    self.launchImageView.frame = self.contentView.bounds;
    self.webView.frame = self.contentView.bounds;
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

@end
